Page({
  data: {
    costShow: false,
    showModal: false,
    group: {
      order: '订单',
      recharge: '充值'
    },
    channel: [
      {
        key: 'balance',
        text: '余额',
        type: 'danger',
        plain: true
      }, {
        key: 'wechat',
        text: '微信',
        type: 'green',
        plain: true
      }, {
        key: 'cancel',
        text: '取消',
        type: 'grey',
        plain: true
      }
    ],
    payParams: {
      balance: {
        payType: 5,
        tradeType: 'default',
      },
      wechat: {
        payType: 1,
        tradeType: 'mini_program',
      }
    }
  },
  onLoad: function (options) {
    this.setData({
      now: wx.time.curUnix(),
      id: options.id,
      type: options.type || 'order',
      money: options.money
    });
    this.getCode();
  },
  onShow: async function () {
    if (await wx.user.hasLogin()) {
      if (this.data.type == 'order') {
        wx.util.request('order.detail', {
          query: `id=${this.data.id}`
        }).then(order => {
          this.setData({
            order: order
          });
        }).catch(err => {
          console.log(err);
        });
        wx.util.request('user.account', {
          query: `id=${wx.getStorageSync('rf_member').id}`
        }).then(account => {
          this.setData({
            [`channel[0].text`]: `${this.data.channel[0].text}（${account.user_money}）`
          });
        });
      } else {
        let channel = this.data.channel;
        channel.splice(0, 1);
        this.setData({
          order: {
            pay_money: this.data.money,
            order_status: 0
          },
          channel: channel
        });
      }
    }
  },
  getCode: async function () {
    wx.login({
      success: res => {
        this.data.code = res.code;
      },
      fail() {
        wx.util.toast('微信繁忙，请稍后重试');
      }
    });
  },
  myOrder: function () {
    wx.redirectTo({
      url: "../order/my"
    });
  },
  costDetail: function () {
    let costShow = this.data.costShow;
    this.setData({
      costShow: !costShow,
      displayStyle: `top: ${costShow ? '-360rpx' : '250rpx'};opacity: ${costShow ? 0 : 1}`
    });
  },
  channel: function () {
    this.setData({
      showModal: true
    });
  },
  payment: async function (e) {
    let key = e.detail.key,
        data = this.data;
    if (key === 'cancel') {
      this.hideModal();
      return;
    }
    // wx.login返回的code仅5分钟有效
    if (data.now + 300 <= wx.time.curUnix()) {
      await this.getCode();
    }
    wx.util.request('common.payment', {
      query: `code=${data.code}`,
      body: {
        order_group: data.type,
        pay_type: data.payParams[key].payType,
        trade_type: data.payParams[key].tradeType,
        data: JSON.stringify((data.type == 'order' ? {order_id: data.id} : {money: data.money}))
      }
    }).then(res => {
      if (!res.payStatus) {
        console.log(res.config.return_msg);
        wx.util.toast('收银台小伙伴偷懒去了，请稍后再来或使用“余额”支付');
        return;
      }
      if (key == 'wechat') {
        // 调起小程序支付接口
        let params = res.config;
        wx.requestPayment({
          timeStamp: params.timestamp,
          nonceStr: params.nonceStr,
          package: params.package,
          signType: 'MD5',
          paySign: params.paySign,
          success() {
            this.result();
          },
          fail(res) {
            if (res.errMsg != 'requestPayment:fail cancel') {
              wx.util.toast(res.errMsg);
            }
          }
        });
      } else {
        this.result();
      }
    });
  },
  hideModal: function () {
    this.setData({
      showModal: false
    });
  },
  result: function () {
    wx.reLaunch({
      url: `result?id=${this.data.id}`,
    });
  }
})